package mywebsocket

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

type Broadcaster struct {
	manager *Manager
}

func NewBroadcaster(m *Manager) *Broadcaster {
	return &Broadcaster{manager: m}
}

// Gin路由处理器示例
func (b *Broadcaster) BroadcastHandler(c *gin.Context) {
	msg := c.Query("message")
	b.Broadcast([]byte(msg))
	c.JSON(200, gin.H{"status": "broadcast success"})
}

func (b *Broadcaster) Broadcast(message []byte) {
	for _, conn := range b.manager.GetAll() {
		conn.WriteMessage(websocket.TextMessage, message)
	}
}

func (b *Broadcaster) SendTo(conn *websocket.Conn, message []byte) error {
	return conn.WriteMessage(websocket.TextMessage, message)
}
